package com.rlz.framemm.util;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.rlz.base.app.Base;
import com.rlz.base.util.ThreadUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.ref.WeakReference;

import androidx.annotation.NonNull;

/**
 * Created by RLZ
 * on 2021/4/26
 */
public class CopyManager {
    private static final int SUCCESS = 1;
    private static final int FAILED = 0;
    private volatile boolean mIsSuccess;
    private String mErrorStr;
    private Handler mHandler;


    public CopyManager() {

    }


    private static class FileHandler extends Handler {

        private final FileOperateCallback mOperateCallback;

        public FileHandler(@NonNull Looper looper, FileOperateCallback callback) {
            super(looper);
            WeakReference<FileOperateCallback> reference = new WeakReference<>(callback);
            mOperateCallback = reference.get();
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            if (mOperateCallback != null) {
                if (msg.what == SUCCESS) {
                    mOperateCallback.onSuccess();
                }
                if (msg.what == FAILED) {
                    mOperateCallback.onFailed(msg.obj.toString());
                }
            }
        }
    }

    public void copy2SD(final String srcPath, final String sdPath, FileOperateCallback callback) {
        if (mHandler == null)
            mHandler = new FileHandler(Looper.getMainLooper(), callback);
        ThreadUtil.getThreadPool().execute(() -> {
            copy2Dst(srcPath, sdPath);
            if (mIsSuccess)
                mHandler.obtainMessage(SUCCESS).sendToTarget();
            else
                mHandler.obtainMessage(FAILED, mErrorStr).sendToTarget();
        });
    }

    private void copy2Dst(String srcPath, String dstPath) {
        Context context = Base.obtain().getApplicationContext();
        try {
            String[] fileNames = context.getAssets().list(srcPath);
            if (fileNames.length > 0) {
                File file = new File(context.getExternalFilesDir(null), dstPath);
                if (!file.exists()) file.mkdirs();
                for (String fileName : fileNames) {
                    if (!srcPath.equals("")) { // assets 文件夹下的目录
                        copy2Dst(srcPath + File.separator + fileName, dstPath + File.separator + fileName);
                    } else { // assets 文件夹
                        copy2Dst(fileName, dstPath + File.separator + fileName);
                    }
                }
            } else {
                File outFile = new File(context.getExternalFilesDir(null), dstPath);
                InputStream is = context.getAssets().open(srcPath);
                FileOutputStream fos = new FileOutputStream(outFile);
                byte[] buffer = new byte[2048];
                int byteCount;
                while ((byteCount = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, byteCount);
                }
                fos.flush();
                is.close();
                fos.close();
            }
            mIsSuccess = true;
        } catch (Exception e) {
            e.printStackTrace();
            mErrorStr = e.getMessage();
            mIsSuccess = false;
        }
    }

    public interface FileOperateCallback {
        void onSuccess();

        default void onFailed(String error) {
        }
    }
}
